import { useLayoutEffect } from "react";
import { useEffect } from "react";
import { useState, useRef } from "react";

const MyUseLayoutEffect = () => {
  const [count, setCount] = useState(0)
  const hRef = useRef(null)

  useEffect(() => {
    console.log("1. 状态改变时，执行useEffect");
    let r = Math.random() * 255;
    let g = Math.random() * 255;
    let b = Math.random() * 255;

    const pre = Date.now();
    console.log(pre);
    // 如果2个时间只差，小于1000，就继续循环；
    while (Date.now() - pre < 1000) {
      console.log(123);
    }
    hRef.current.style.backgroundColor = `rgb(${r},${g}, ${b})`
  }, [count])

  // 当在 useEffect 里面的操作需要处理 DOM,并且会改变页面的样式,就需要用 useLayoutEffect 替换 useEffect,否则可能会出现闪屏问题。
  /*   useLayoutEffect(() => {
  
      // 当业务逻辑需要很长的处理时间时，会阻塞页面的渲染
      let r = Math.random() * 255;
      let g = Math.random() * 255;
      let b = Math.random() * 255;
  
  
      const pre = Date.now();
      
      while (Date.now() - pre < 1000) {
        console.log(123);
      }
      hRef.current.style.backgroundColor = `rgb(${r},${g}, ${b})`
      console.log("2. 状态改变时，执行useLayoutEffect");
  
    }, [count]); */
  return (
    <div>
      <h1 ref={hRef}>MyUseLayoutEffect组件</h1>
      <button type="button" onClick={() => {
        setCount(count + 1)
      }}>修改count: {count}</button>
    </div>
  )
}

export default MyUseLayoutEffect;